package com.example.casper.Experiment2024;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;


import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;


import com.example.casper.Experiment2024.data.DataBank;
import com.example.casper.Experiment2024.data.book;



import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link ShoppingListFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class ShoppingListFragment extends Fragment
{

    public ShoppingListFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @return A new instance of fragment ShoppingListFragment.
     */
    public static ShoppingListFragment newInstance() {
        ShoppingListFragment fragment = new ShoppingListFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState)
    {

        View rootViewer=inflater.inflate(R.layout.fragment_shopping_list, container, false);

        recyclerView = rootViewer.findViewById(R.id.recyclerview_items);
        recyclerView.setLayoutManager(new LinearLayoutManager(requireActivity()));



        DataBank databank=new DataBank(requireActivity());
        bookList=databank.readItems();

        if(bookList.isEmpty())
            bookList.add(new book(R.drawable.book_no_name, "创新工程实践", "￥56"));

        adapter = new RecyclerViewBookAdapter(requireActivity(), bookList);
        recyclerView.setAdapter(adapter);
        registerForContextMenu(recyclerView);

        return rootViewer;
    }

    private RecyclerView recyclerView;
    private RecyclerViewBookAdapter adapter;
    private List<book> bookList;
    private ActivityResultLauncher<Intent> addItemLauncher;
    private ActivityResultLauncher<Intent> updateItemLauncher;

    @Override
    public boolean onContextItemSelected(MenuItem itemMenu) {
        //item.getOrder()
        switch (itemMenu.getItemId()) {
            case 0:
                Intent intentAdd = new Intent(this.getContext(), BookItemDetailsActivity.class);
                intentAdd.putExtra("position", itemMenu.getOrder());
                addItemLauncher.launch(intentAdd);
                break;
            case 1:
                AlertDialog.Builder builder = new AlertDialog.Builder(this.getContext());
                builder.setTitle("Delete Data");
                builder.setMessage("Are you sure you want to delete this data?");
                builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        bookList.remove(itemMenu.getOrder());
                        adapter.notifyItemRemoved(itemMenu.getOrder());
                        DataBank databank=new DataBank(ShoppingListFragment.this.getContext());
                        databank.saveItems(bookList);

                    }
                });
                builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                AlertDialog dialog = builder.create();
                dialog.show();
                break;
            case 2:
                Intent intentUpdate = new Intent(this.getContext(), BookItemDetailsActivity.class);
                book item = bookList.get(itemMenu.getOrder());
                intentUpdate.putExtra("name", item.getTitle());
                intentUpdate.putExtra("price", item.getPrice());
                intentUpdate.putExtra("position", itemMenu.getOrder());
                updateItemLauncher.launch(intentUpdate);
                break;
            default:
                return super.onContextItemSelected(itemMenu);
        }
        return true;
    }

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        if (getArguments() != null)
        {

        }
        addItemLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    if (result.getResultCode() == Activity.RESULT_OK) {
                        Intent data = result.getData();
                        assert data != null;
                        String name = data.getStringExtra("name");
                        String price = data.getStringExtra("price");
                        int position = data.getIntExtra("position", 0)+1;
                        bookList.add(position, new book(R.drawable.book_no_name, name, price));
                        adapter.notifyItemInserted(position);
                        DataBank databank=new DataBank(this.getContext());
                        databank.saveItems(bookList);
                    } else if (result.getResultCode() == Activity.RESULT_CANCELED) {
                        Toast.makeText(this.getContext(), "操作已取消", Toast.LENGTH_SHORT).show();
                    }
                }
        );

        updateItemLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    if (result.getResultCode() == Activity.RESULT_OK) {
                        Intent data = result.getData();
                        int position = data.getIntExtra("position",0);
                        String name=data.getStringExtra("name");
                        String price = data.getStringExtra("price");

                        book item = bookList.get(position);
                        item.setPrice(price);
                        item.setTitle(name);
                        adapter.notifyItemChanged(position);
                        DataBank databank=new DataBank(this.getContext());
                        databank.saveItems(bookList);
                    } else if (result.getResultCode() == Activity.RESULT_CANCELED) {

                    }
                });
    }

    private static class RecyclerViewBookAdapter extends RecyclerView.Adapter<com.example.casper.Experiment2024.RecyclerViewBookAdapter.BookViewHolder>
    {

        private final Context context;
        private final List<book> bookList;
        private final int clickedPosition = -1; // 保存点击位置

        public RecyclerViewBookAdapter(Context context, List<book> bookList) {
            this.context = context;
            this.bookList = bookList;
        }

        @NonNull
        @Override
        public com.example.casper.Experiment2024.RecyclerViewBookAdapter.BookViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(context).inflate(R.layout.book_item, parent, false);
            return new com.example.casper.Experiment2024.RecyclerViewBookAdapter.BookViewHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull com.example.casper.Experiment2024.RecyclerViewBookAdapter.BookViewHolder holder, int position) {
            book book = bookList.get(position);
            holder.imageViewBookCover.setImageResource(book.getCoverResourceId());
            holder.textViewBookName.setText(book.getTitle());
            holder.textViewBookPrice.setText(book.getPrice());
        }

        @Override
        public int getItemCount() {
            return bookList.size();
        }

        public class BookViewHolder extends RecyclerView.ViewHolder implements View.OnCreateContextMenuListener {
            public ImageView imageViewBookCover;
            public TextView textViewBookName;
            public TextView textViewBookPrice;

            public BookViewHolder(@NonNull View itemView) {
                super(itemView);
                imageViewBookCover = itemView.findViewById(R.id.image_view_book_cover);
                textViewBookName = itemView.findViewById(R.id.text_view_book_name);
                textViewBookPrice = itemView.findViewById(R.id.text_view_book_price);

                itemView.setOnCreateContextMenuListener(this);
            }

            @Override
            public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
                menu.setHeaderTitle("具体操作");

                menu.add(0, 0, this.getAdapterPosition(), "添加" + this.getAdapterPosition());
                menu.add(0, 1, this.getAdapterPosition(), "删除" + this.getAdapterPosition());
                menu.add(0, 2, this.getAdapterPosition(), "修改" + this.getAdapterPosition());
            }
        }
    }
}